package net.aiion.weave.impl.painters.stream.identicons;

import java.awt.Color;
import java.io.IOException;

import net.aiion.weave.impl.painters.PaintBrushMessage;
import net.aiion.weave.impl.painters.stream.AbstractStreamBrush;
import net.aiion.weave.spi.messaging.annotations.Receives;
import net.aiion.weave.spi.naming.annotations.Named;
import net.aiion.weave.spi.naming.annotations.NotScoped;
import net.aiion.weave.spi.painters.PaintException;
import net.aiion.weave.spi.painters.stream.identicons.Identicon;
import net.aiion.weave.spi.painters.stream.identicons.IdenticonPaintBrush;
import net.aiion.weave.spi.routing.Route;

@Named
@NotScoped
public class IdenticonPaintBrushImpl extends AbstractStreamBrush implements IdenticonPaintBrush
{
    private static final String IDENTICON_EXTENSION = "vid";

    private static final int IDENTICON_SIZE = 256;
    private static final Color IDENTICON_BACKGROUND_COLOR = Color.WHITE;

    public IdenticonPaintBrushImpl() {
    }

    @Receives("net.aiion.weave.painters")
    public Object resolvePaintBrush(final PaintBrushMessage aPaintBrushMessage) {
        final Route route = aPaintBrushMessage.getRoute();
        if (IDENTICON_EXTENSION.equals(route.getExtension())) {
            return this;
        }

        return null;
    }

    @Override
    public void writeData(final byte[] data) {
        try {
            final Identicon i = IdenticonFactory.getInstance().createIdenticon(data);
            i.setSize(IDENTICON_SIZE);
            i.setBackgroundColor(IDENTICON_BACKGROUND_COLOR);
            i.drawIdenticon(getOutputStream());
        } catch (final IOException e) {
            throw new PaintException(e);
        }
    }

    @Override
    public void writeData(final String data) {
        writeData(data.getBytes());
    }

    @Override
    public void closeBrush() {
    }
}
